import os
import re
import sys
import subprocess
import argparse
import platform
ARCH = platform.machine()

cmd = "yum list --installroot=/tmp --available | grep -E '\.%s|\.noarch' | grep -v 'debugsource' | grep -v 'debuginfo'| awk '{print $1}' > allist" % ARCH
print(cmd)
if os.system(cmd) == 0:
    pass
else:
    sys.exit(1)

rpmlist=[]
excludelist = ""
deletelist = []
cmd="yumdownloader --resolve --installroot=/tmp --destdir=/tmp $(cat allist | tr '\n' ' ')"
p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
out, err = p.communicate()
with open("checklog.txt", 'w') as f:
    while err:
        print("============== %s ============" % err)
        if "Problem" not in err and "No package" not in err:
            break
        for line in err.splitlines():
            if "requires" in line:
                f.write("%s\n" % line)
                if "package" in line:
                    pkg = line.split("package")[1].split("requires")[0].strip()
                    if pkg not in rpmlist:
                        rpmlist.append(pkg)
            if "needed by" in line:
                f.write("%s\n" % line)
                pkg = line.split("needed by")[1].strip()
                if pkg not in rpmlist:
                    rpmlist.append(pkg)
        for p in rpmlist:
            excludelist = excludelist + " -x %s" % p
        cmd="yumdownloader --resolve --installroot=/tmp --destdir=/tmp $(cat allist | tr '\n' ' ') %s" % excludelist 
        p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
        out, err = p.communicate()
        if err:
            for line in err.splitlines():
                if "No package" in line:
                    pkg = line.split("No package")[1].split("available")[0].strip()
                    cmd = "sed -i '/%s/d' allist" % pkg
                    if os.system(cmd) == 0:
                        pass
                    if pkg not in deletelist:
                        deletelist.append(pkg)
        cmd="yumdownloader --resolve --installroot=/tmp --destdir=/tmp $(cat allist | tr '\n' ' ') %s" % excludelist 
        p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
        out, err = p.communicate()
        print("++++++++++ %s ++++++++++++" % out)
for p in deletelist:
    cmd = "echo %s >> deletelist" % p
    if os.system(cmd) == 0:
        pass
cmd = "sed -i 's/\.%s//g' deletelist && sed -i 's/\.noarch//g' deletelist" % ARCH
os.system(cmd)
